package com.shenzhen.horselive.ui.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;

import com.flqy.baselibrary.utils.L;
import com.gyf.immersionbar.ImmersionBar;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.LainTongAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.BaseFragment;
import com.shenzhen.horselive.beans.AllCityLordBean;
import com.shenzhen.horselive.beans.NewsBean;
import com.shenzhen.horselive.databinding.FragmentLianTongBinding;
import com.shenzhen.horselive.databinding.HeadLiantongBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.activity.CityPartnerActivity;
import com.shenzhen.horselive.ui.activity.MapViewActivity;
import com.shenzhen.horselive.ui.activity.OpenCardActivity;
import com.shenzhen.horselive.ui.activity.PhoneRechargeActivity;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptor;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.IOverlay;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LianTongFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LianTongFragment extends BaseFragment {

    public static LianTongFragment newInstance() {
        LianTongFragment fragment = new LianTongFragment();
        return fragment;
    }

    FragmentLianTongBinding  binding;

    @Override
    protected View getContentView(LayoutInflater inflater, ViewGroup viewGroup) {
        binding = FragmentLianTongBinding.inflate(getLayoutInflater(),viewGroup,false);
        initViews();
        initData();
        return binding.getRoot();
    }


    private void   getAllMastersList()
    {
        //加载地图标记点
        ApiFactory.getApiService().allMasterList(User.get().getMyInfo().getToken(),"2")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<AllCityLordBean>(this) {
                    @Override
                    protected void onNextInActive(AllCityLordBean allCityLordBean) {
                        if (allCityLordBean.isSuccess())
                        {
                            if (allCityLordBean.getData()!=null)
                                addMarkToMap(allCityLordBean.getData());

                        }else
                        {
                            showToast(allCityLordBean.getErrMessage());
                        }
                    }
                });
    }

    private void initData() {
       //加载咨询
       ApiFactory.getApiService().news(User.get().getMyInfo().getToken())
               .compose(SchedulersCompat.applyIoSchedulers())
               .safeSubscribe(new LoadingViewObserver<NewsBean>(this) {
                   @Override
                   protected void onNextInActive(NewsBean newsBean) {
                       if (newsBean.isSuccess())
                       {
                           adapter.setNewData(newsBean.getData());
                           binding.recyclerview.setAdapter(adapter);
                       }else
                       {
                           showToast(newsBean.getErrMessage());
                       }
                   }
               });


    }

    /**
     * 添加地图标点
     * @param data
     */
    private void addMarkToMap(List<AllCityLordBean.DataBean> data) {
        //地图正常显示
        BitmapDescriptor custom = BitmapDescriptorFactory.fromResource(R.mipmap.ico_red_qi);
        List<IOverlay> overlays = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
          LatLng  latLng =   new LatLng(Double.parseDouble(data.get(i).getLat()), Double.parseDouble(data.get(i).getLng()));
            Marker marker = tencentMap.addMarker(new MarkerOptions(latLng)
                    .icon(custom)
                    .anchor(0.5f, 1)
                    );
            overlays.add(marker);
        }
        tencentMap.moveCamera(CameraUpdateFactory.newCameraPosition(
                tencentMap.calculateZoomToSpanLevel(
                        overlays, null,
                        0, 0, 0, 0)));
    }

    LainTongAdapter  adapter;
    //初始化views
    private void initViews() {
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new LainTongAdapter(R.layout.item_liantong);
//        binding.recyclerview.setAdapter(adapter);
        adapter.addHeaderView(getHead());
    }

    HeadLiantongBinding  headbinding;
    TencentMap  tencentMap;
    //初始化头部
    private  View  getHead()
    {
        headbinding = HeadLiantongBinding.inflate(getLayoutInflater());
        //地图添加标记点
        tencentMap = headbinding.headMap.getMap();
        tencentMap.setOnMapLoadedCallback(new TencentMap.OnMapLoadedCallback() {
            public void onMapLoaded() {
                getAllMastersList();
            }
        });
        //标记点击事件
       tencentMap.setOnMarkerClickListener(new TencentMap.OnMarkerClickListener() {
           @Override
           public boolean onMarkerClick(Marker marker) {
               startActivity(new Intent(getContext(), MapViewActivity.class));
               return true;
           }
       });
       tencentMap.setOnMapClickListener(new TencentMap.OnMapClickListener() {
           @Override
           public void onMapClick(LatLng latLng) {
               startActivity(new Intent(getContext(), MapViewActivity.class));
           }
       });
        //开卡
        headbinding.imgKaika.setOnClickListener(onClickListener);
        headbinding.imgHehuo.setOnClickListener(onClickListener);
        headbinding.imgHuafei.setOnClickListener(onClickListener);
        return headbinding.getRoot();
    }

    long  mlasttime;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            long  nowtime = System.currentTimeMillis();
            if ((nowtime-mlasttime)/1000<1)
                return;
            mlasttime =nowtime;
            switch (v.getId())
            {
                case R.id.img_kaika:
                    startActivity(new Intent(getContext(), OpenCardActivity.class));
                    break;
                case R.id.img_hehuo:
                    //合伙人
                    startActivity(new Intent(getContext(), CityPartnerActivity.class));
                    break;
                case R.id.img_huafei:
                    startActivity(new Intent(getContext(), PhoneRechargeActivity.class));
                    break;
            }
        }
    };





    @Override
    public void onStart() {
        super.onStart();
        if (headbinding!=null)
        {
            headbinding.headMap.onStart();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (headbinding!=null)
        {
            headbinding.headMap.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (headbinding!=null)
        {
            headbinding.headMap.onPause();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (headbinding!=null)
        {
            headbinding.headMap.onStop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (headbinding!=null)
        {
            headbinding.headMap.onDestroy();
        }
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();
    }
}